import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routeList = () => {
  var list = []
  const routerModules = require.context('./modules', true, /\.routes\.js/)
  routerModules.keys().forEach(key => {
    list = list.concat(routerModules(key).default)
  })
  list.sort(compare('sort'))
  return list
}

const compare = (prop) => {
  return function (obj1, obj2) {
    let val1 = obj1[prop] || 0
    let val2 = obj2[prop] || 0
    if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
      val1 = Number(val1);
      val2 = Number(val2);
    }
    if (val1 > val2) {
      return -1;
    } else if (val1 < val2) {
      return 1;
    } else {
      return 0;
    }
  }
}

const router = new VueRouter({
  //页面初始化置顶 启用history模式，去除路由上的#
  scrollBehavior: () => ({ y: 0 }),
  routes: routeList(),
  mode: 'history'
})

export default router

// 路由keepAlive缓存，组件回退缓存未销毁统一处理

var history = []

Vue.mixin({
  beforeRouteLeave(to, _, next) {
    if (history.includes(to.path)) {
      // this.$destroy()
      history = history.filter(item => item != to.path)
    }
    next()
  }
})

router.beforeEach((to, _, next) => {
  history.push(to.path)
  next()
})

//处理重复路由跳转时报错
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(to) {
  return VueRouterPush.call(this, to).catch(err => err)
}

// end
